package me.zhengjie.modules.realestate.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mchange.lang.IntegerUtils;
import lombok.AllArgsConstructor;
import me.zhengjie.base.PageInfo;
import me.zhengjie.base.QueryHelpMybatisPlus;
import me.zhengjie.base.impl.CommonServiceImpl;
import me.zhengjie.modules.ImgIntroduction.domain.ImageIntroduction;
import me.zhengjie.modules.ImgIntroduction.service.mapper.ImageIntroductionMapper;
import me.zhengjie.modules.consultant.service.mapper.ConsultantMapper;
import me.zhengjie.modules.detail.domain.RealEstateProjectDetail;
import me.zhengjie.modules.detail.service.mapper.RealEstateProjectDetailMapper;
import me.zhengjie.modules.housetype.domain.HouseType;
import me.zhengjie.modules.housetype.service.mapper.HouseTypeMapper;
import me.zhengjie.modules.location.domain.Location;
import me.zhengjie.modules.location.service.mapper.LocationMapper;
import me.zhengjie.modules.realestate.service.dto.*;
import me.zhengjie.modules.system.domain.DictDetail;
import me.zhengjie.modules.system.service.mapper.DictDetailMapper;
import me.zhengjie.modules.thumbnail.domain.Thumbnail;
import me.zhengjie.modules.thumbnail.service.mapper.ThumbnailMapper;
import me.zhengjie.utils.*;
import me.zhengjie.modules.realestate.domain.RealEstateProject;
import me.zhengjie.modules.realestate.service.RealEstateProjectService;
import me.zhengjie.modules.realestate.service.mapper.RealEstateProjectMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import me.zhengjie.modules.consultant.domain.Consultant;
import org.springframework.data.domain.Pageable;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author TianI
 * @date 2022-02-15
 */
@Service
@AllArgsConstructor
// @CacheConfig(cacheNames = RealEstateProjectService.CACHE_KEY)
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class RealEstateProjectServiceImpl extends CommonServiceImpl<RealEstateProjectMapper, RealEstateProject> implements RealEstateProjectService {

    // private final RedisUtils redisUtils;
    private final RealEstateProjectMapper realEstateProjectMapper;
    private final RealEstateProjectDetailMapper repDetailsMapper;
    private final ConsultantMapper consultantMapper;
    private final ImageIntroductionMapper imageIntroductionMapper;
    private final HouseTypeMapper houseTypeMapper;
    private final LocationMapper locationMapper;
    private final ThumbnailMapper thumbnailMapper;
    private final DictDetailMapper dictDetailMapper;

    @Override
    public PageInfo<RealEstateProjectDto> queryAll(RealEstateProjectQueryParam query, Pageable pageable) {
        IPage<RealEstateProject> queryPage = PageUtil.toMybatisPage(pageable);
        IPage<RealEstateProject> page = realEstateProjectMapper.selectPage(queryPage, QueryHelpMybatisPlus.getPredicate(query));
        return ConvertUtil.convertPage(page, RealEstateProjectDto.class);
    }

    @Override
    public List<RealEstateProjectDto> queryAll(RealEstateProjectQueryParam query) {
        return ConvertUtil.convertList(realEstateProjectMapper.selectList(QueryHelpMybatisPlus.getPredicate(query)), RealEstateProjectDto.class);
    }

    @Override
    public RealEstateProject getById(Long id) {
        return realEstateProjectMapper.selectById(id);
    }

    @Override
    // @Cacheable(key = "'id:' + #p0")
    public RealEstateProjectDto findById(Long id) {
        return ConvertUtil.convert(getById(id), RealEstateProjectDto.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(RealEstateProjectDto resources) {
        RealEstateProject entity = ConvertUtil.convert(resources, RealEstateProject.class);
        return realEstateProjectMapper.insert(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateById(RealEstateProjectDto resources) {
        RealEstateProject entity = ConvertUtil.convert(resources, RealEstateProject.class);
        int ret = realEstateProjectMapper.updateById(entity);
        // delCaches(resources.id);
        return ret;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeByIds(Set<Long> ids) {
        // delCaches(ids);
        return realEstateProjectMapper.deleteBatchIds(ids);
    }

    @Override
    public void saveRep(RealEstateProjectSaveVo vo) {

        Long id = Math.abs(UuidUtils.getId());
        RealEstateProjectDetail repDetails = new RealEstateProjectDetail();
        DetailVo detail = vo.getDetail();
        repDetails.setRealEstateProjectId(id);
        repDetails.setRealEstateProjectDetailId(id);
        repDetails.setRealEstateProjectName(detail.getRealEstateProjectName());
        repDetails.setPropertyCategory(detail.getPropertyCategory());
        repDetails.setProjectFeatures(detail.getProjectFeatures());
        repDetails.setBuildingCategory(detail.getBuildingCategory());
        repDetails.setPropertyDevelopers(detail.getPropertyDevelopers());
        repDetails.setProjectAddress(detail.getProjectAddress());
        repDetails.setProjectLabel(detail.getProjectLabel());
        repDetails.setCoveredArea(detail.getCoveredArea());
        repDetails.setConsultingTelephone(detail.getConsultingTelephone());
        repDetails.setDecorateSituation(detail.getDecorateSituation());
        repDetails.setDeliverTime(DateUtil.format(detail.getDeliverTime(),"yyyy-MM-dd HH:mm:ss"));
        repDetails.setFloorCondition(detail.getFloorCondition());
        repDetails.setSaleAddress(detail.getSaleAddress());
        repDetails.setFloorSpace(detail.getFloorSpace());
        repDetails.setPlotRatio(String.valueOf(detail.getPlotRatio()));
        repDetails.setBuildingTotal(detail.getBuildingTotal());
        repDetails.setHouseholdsTotal(detail.getHouseholdsTotal());
        repDetails.setGreeningRate(String.valueOf(detail.getGreeningRate()));
        repDetails.setPropertyCompanyName(detail.getPropertyCompanyName());
        repDetails.setPropertyFee(detail.getPropertyFee());
        repDetails.setProjectBrief(detail.getProjectBrief());
        repDetails.setRecordName(detail.getRecordName());
        repDetails.setParkingSpaceTotal(detail.getParkingSpaceTotal());
        repDetails.setMinimumPrice(new BigDecimal(detail.getMinimumPrice()));
        repDetails.setMaximumPrice(new BigDecimal(detail.getMaximumPrice()));
        repDetails.setOpenTime(DateUtil.format(detail.getOpenTime(),"yyyy-MM-dd HH:mm:ss"));
        repDetails.setOnSale(detail.isOnSale()?0:1);
        repDetailsMapper.insert(repDetails);

        DictDetail dictDetail = new DictDetail();
        dictDetail.setDictSort(999);
        dictDetail.setDictId(7L);
        dictDetail.setLabel(detail.getRealEstateProjectName());
        dictDetail.setValue(id.toString());
        dictDetailMapper.insert(dictDetail);

        Long dcompanyId = vo.getDcompanyId();
        RealEstateProject realEstateProject = new RealEstateProject();
        realEstateProject.setDcompanyId(dcompanyId);
        realEstateProject.setRealEstateProjectDetailId(id);
        realEstateProjectMapper.insert(realEstateProject);

        List<ConsultantVo> consultant = vo.getConsultant();
        for (ConsultantVo item : consultant) {
            Consultant consultant1 = new Consultant();
            if (!StringUtils.isEmpty(item.getName()) && !StringUtils.isEmpty(item.getPhone()) && !StringUtils.isEmpty(item.getAvatar())) {
                consultant1.setConsultantName(item.getName());
                consultant1.setConsultantPhone(item.getPhone());
                consultant1.setConsultantAvatar(item.getAvatar());
                consultant1.setRealEstateProjectId(id);
                consultantMapper.insert(consultant1);
            }

        }
        List<String> introduce = vo.getIntroduce();
        for (String i : introduce) {
            ImageIntroduction imageIntroduction = new ImageIntroduction();
            imageIntroduction.setRealEstateProjectId(id);
            imageIntroduction.setImageUrl(i);
            imageIntroductionMapper.insert(imageIntroduction);
        }
        List<HouseTypevo> houseType = vo.getHouseType();
        for (HouseTypevo type : houseType) {
            HouseType houseType1 = new HouseType();
            if (!StringUtils.isEmpty(type.getHouseType())
                    && !StringUtils.isEmpty(type.getHouseTypeAnalysis())
                    && !StringUtils.isEmpty(type.getHouseTypePrice())
                    && !StringUtils.isEmpty(type.getHouseTypeDistribution())
                    && !StringUtils.isEmpty(type.getHouseTypeUrl())
                    && !StringUtils.isEmpty(type.getHouseTypeCategory())
                    && !StringUtils.isEmpty(type.getHouseTypeName())) {
                houseType1.setHouseType(type.getHouseType());
                houseType1.setHouseTypeAnalysis(type.getHouseTypeAnalysis());
                houseType1.setHouseTypeCategory(type.getHouseTypeCategory());
                houseType1.setHouseTypeName(type.getHouseTypeName());
                houseType1.setHouseTypePrice(type.getHouseTypePrice());
                houseType1.setHouseTypeDistribution(type.getHouseTypeDistribution());
                houseType1.setHouseTypeUrl(type.getHouseTypeUrl());
                houseType1.setRealEstateProjectId(id);
                houseTypeMapper.insert(houseType1);
            }
        }
        List<LocationVo> location = vo.getLocation();
        for (LocationVo locationVo : location) {
            Location location1 = new Location();
            if (!StringUtils.isEmpty(locationVo.getLocationName())&&!StringUtils.isEmpty(String.valueOf(locationVo.getNum()))&&!StringUtils.isEmpty(locationVo.getLocationCategoryId())) {
                location1.setLocationName(locationVo.getLocationName());
                location1.setLocationDistance(String.valueOf(locationVo.getNum()));
                location1.setLocationCategoryId(locationVo.getLocationCategoryId());
                location1.setRealEstateProjectId(id);
                locationMapper.insert(location1);
            }

        }
        List<String> thumbnail = vo.getThumbnail();
        for (String t : thumbnail) {
            Thumbnail thumbnail1 = new Thumbnail();
            thumbnail1.setThumbnailUrl(t);
            thumbnail1.setRealEstateProjectId(id);
            thumbnailMapper.insert(thumbnail1);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeById(Long id) {
        Set<Long> set = new HashSet<>(1);
        set.add(id);
        return this.removeByIds(set);
    }

    /*
    private void delCaches(Long id) {
        redisUtils.delByKey(CACHE_KEY + "::id:", id);
    }

    private void delCaches(Set<Long> ids) {
        for (Long id: ids) {
            delCaches(id);
        }
    }*/

    /*
    @Override
    public void download(List<RealEstateProjectDto> all, HttpServletResponse response) throws IOException {
      List<Map<String, Object>> list = new ArrayList<>();
      for (RealEstateProjectDto realEstateProject : all) {
        Map<String,Object> map = new LinkedHashMap<>();
              map.put("关联分公司主键id", realEstateProject.getDcompanyId());
              map.put("关联房产户型主键id", realEstateProject.getHouseTypeId());
              map.put("关联置业顾问主键id", realEstateProject.getConsultantId());
              map.put("关联项目区位主键id", realEstateProject.getLocationId());
              map.put("房产项目详情主键id", realEstateProject.getRealEstateProjectDetailId());
        list.add(map);
      }
      FileUtil.downloadExcel(list, response);
    }*/
}
